﻿using Leadshine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MotionIoLib
{
   public class IoCtrl_LTNMC : IoCtrl
    {
        private ushort _ConnecNo = 0;

        public IoCtrl_LTNMC(int nIndex, ulong nCardNo)
            : base(nIndex, nCardNo)
        {
        }

        public override void DeInit()
        {
            short res = LTDMC.nmc_set_connect_state((ushort)_ConnecNo, 2, 0, 0);//连接控制器
        }

        public override bool Init()
        {
            m_bOpen = false;
            _ConnecNo = (ushort)m_nCardNo;
            short res = LTDMC.dmc_board_init();
            res = LTDMC.nmc_set_connect_state((ushort)_ConnecNo, 2, 0, 0);//断开控制器
            res = LTDMC.nmc_set_connect_state((ushort)_ConnecNo, 2,1,0 );//连接控制器
            if (res != 0)
            {
               
                return false;
            }
            else
            {
                ushort nodeNum = 0;
                ushort state = 0;
                short val = LTDMC.nmc_get_connect_state((ushort)_ConnecNo, ref nodeNum, ref state);
                m_bOpen = true;
            }          
            return true;
        }

        public override bool InStopDisenable(int nIndex)
        {
            throw new NotImplementedException();
        }

        public override bool InStopEnable(int nIndex)
        {
            throw new NotImplementedException();
        }

        public override bool ReadIOIn(ref int nData)
        {
            //nData = (int)LTDMC.smc_read_inport(_ConnecNo, 0);
            //return true;
            throw new NotImplementedException();
        }

        public override bool ReadIoInBit(int nIndex)
        {
            int nAxisIndex = (nIndex & 0xff00) >> 8;
            int nBitIndex = nIndex & 0x00ff;

            //输入口
            ushort n = 0;
            LTDMC.nmc_read_inbit(_ConnecNo, (ushort)(nAxisIndex+1), (ushort)nIndex, ref n);
            return n == 0;
        }

        public override bool ReadIOOut(ref int nData)
        {
            throw new NotImplementedException();
        }

        public override bool ReadIoOutBit(int nIndex)
        {
            //输入口
            int nAxisIndex = (nIndex & 0xff00) >> 8;
            int nBitIndex = nIndex & 0x00ff;
            ushort n = 0;
            LTDMC.nmc_read_outbit(_ConnecNo, (ushort)(nAxisIndex+1), (ushort)nIndex, ref n);
            return n == 0;
        }
        public override bool WriteIo(int nData)
        {
            throw new NotImplementedException();
        }

        public override bool WriteIoBit(int nIndex, bool bBit)
        {

            int nAxisIndex = (nIndex & 0xff00) >> 8;
            int nBitIndex = nIndex & 0x00ff;

            short ret = LTDMC.nmc_write_outbit(_ConnecNo, (ushort)(nAxisIndex + 1), (ushort)nIndex, bBit ? (ushort)0 : (ushort)1);
            return true;
        }
    }
}
